//
//  StatusDAL.swift
//  Weibo
//
//  Created by 李振兴 on 15/11/3.
//  Copyright © 2015年 李振兴. All rights reserved.
//

import Foundation
class StatusDAL {
    
    private class func checkChacheData(since_id: Int, max_id: Int) -> [[String: AnyObject]]? {
        
        print("检查本地数据 \(since_id) \(max_id)")
        
        // 0. 用户 id
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else {
            print("用户没有登录")
            return nil
        }
        
        // 1. 准备 SQL
        var sql = "SELECT statusId, status, userId FROM T_Status \n"
        sql += "WHERE userId = \(userId) \n"
        
        if since_id > 0 {           // 下拉刷新
            sql += "    AND statusId > \(since_id) \n"
        } else if max_id > 0 {      // 上拉刷新
            sql += "    AND statusId < \(max_id) \n"
        }
        
        sql += "ORDER BY statusId DESC LIMIT 20;"
        
        print("查询数据 SQL -> " + sql)
        
        // 2. 执行 SQL -> 返回结果集合
        let array = SQLiteManager.sharedManager.execRecordSet(sql)
        
        // 3. 遍历数组 -> dict["status"] JSON 反序列化
        var arrayM = [[String: AnyObject]]()
        for dict in array {
            let jsonData = dict["status"] as! NSData
            // 反序列化 -> 一条完整微博数据字典
            let result = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
            
            // 添加到数组
            arrayM.append(result as! [String : AnyObject])
        }
        
        // 返回结果 － 如果没有查询到数据，会返回一个空的数组
        return arrayM
    }
     class func saveCacheData(array: [[String: AnyObject]]) {
        
        // 0. 用户 id
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else {
            print("用户没有登录")
            return
        }
        
        // 1. 准备 SQL
        /**
        1. 微博 id -> 通过字典获取
        2. 微博 json -> 字典序列化
        3. userId -> 登录的用户
        */
        let sql = "INSERT OR REPLACE INTO T_Status (statusId, status, userId) VALUES (?, ?, ?);"
        SQLiteManager.sharedManager.queue.inTransaction { (db, roolBack) -> Void in
            for dict in array {
                guard let statusId = dict["id"] else{
                    return
                }
                let status = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                if !db.executeUpdate(sql, statusId,status,userId) {
                    print("插入失败")
                    roolBack.memory = true
                    break
                }
            }
            
        }
    }
}